package com.shanks.framework.mq.common.util;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.util.Map;

public class JsonUtil {
    private static final ObjectMapper objectMapper = new ObjectMapper();

    /**
     * 将对象序列化为 JSON 字符串
     *
     * @param obj 要序列化的对象
     * @return JSON 字符串
     */
    public static String toJson(Object obj) {
        try {
            return objectMapper.writeValueAsString(obj);
        } catch (Exception e) {
            throw new RuntimeException("JSON 序列化失败", e);
        }
    }

    /**
     * 将 JSON 字符串反序列化为对象
     *
     * @param json  JSON 字符串
     * @param clazz 目标对象的类型
     * @param <T>   泛型类型
     * @return 反序列化的对象
     */
    public static <T> T fromJson(String json, Class<T> clazz) {
        try {
            return objectMapper.readValue(json, clazz);
        } catch (Exception e) {
            throw new RuntimeException("JSON 反序列化失败", e);
        }
    }


    /**
     * 将对象转换为 JSON 字符串，如果转换过程中发生异常，则返回 null。
     *
     * @param object 要转换的对象
     * @return JSON 字符串，转换失败返回 null
     */
    public static String toJsonQuietly(Object object) {
        try {
            return objectMapper.writeValueAsString(object);
        } catch (Exception e) {
            // 处理异常，静默返回 null
            return null;
        }
    }

    public static String allToJson(Object record) throws JsonProcessingException {

        return objectMapper.writeValueAsString(record);

    }

    // You can add a method for parsing to Map specifically if needed.
    public static Map<String, Object> parseToMap(String json) {
        try {
            return objectMapper.readValue(json, Map.class);
        } catch (Exception e) {
            throw new RuntimeException("Failed to parse JSON to Map", e);
        }
    }
}
